<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/' }">用户管理</el-breadcrumb-item>
    </el-breadcrumb>
  </div>

    <div class="search-container">
      <el-input v-model="searchQuery.userName" placeholder="按用户名搜索" @input="fetchUsers" class="search-input"></el-input>
      <el-input v-model="searchQuery.phone" placeholder="按手机号搜索" @input="fetchUsers" class="search-input"></el-input>
      <el-input v-model="searchQuery.email" placeholder="按邮箱搜索" @input="fetchUsers" class="search-input"></el-input>
      <!-- <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="fetchUsers"
        class="date-picker"
      ></el-date-picker> -->
      <el-button type="primary" @click="fetchUsersSearch">查询</el-button>
      <el-button type="primary" @click="showAddUserDialog">新增用户</el-button>
    </div>

    <!-- 数据列表容器 -->
    <div class="table-container">
      <el-table :data="users" stripe style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="userId" label="ID" width="80"></el-table-column>
        <el-table-column prop="userName" label="用户名" min-width="120"></el-table-column>
        <el-table-column prop="name" label="姓名" min-width="90"></el-table-column>
        <el-table-column prop="sex" label="性别" width="60"></el-table-column>
        <el-table-column prop="age" label="年龄" width="80"></el-table-column>
        <el-table-column prop="address" label="地址" min-width="150"></el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="180"></el-table-column>
        <el-table-column prop="phone" label="手机号" min-width="150"></el-table-column>
        <el-table-column prop="points" label="积分" width="100"></el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button link type="primary" size="small" @click="showEditUserDialog(row)">编辑</el-button>
              <el-button link type="danger" size="small" @click="deleteUser(row.userId)">删除</el-button>
              <el-button link type="warning" size="small" @click="resetPassword(row.userId)">重置密码</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- Add User Dialog -->
    <el-dialog v-model="isAddUserDialogVisible" title="新增用户" class="dialog" width="50%">
      <el-form :model="newUser" :rules="rules" ref="newUserForm" label-width="80px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="newUser.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="newUser.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="newUser.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="newUser.sex" placeholder="选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="newUser.age" :min="0" :max="120"></el-input-number>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="newUser.address"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="newUser.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="newUser.phone"></el-input>
        </el-form-item>
        <el-form-item label="积分" prop="points">
          <el-input-number v-model="newUser.points" :min="0"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddUserDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addUser">添加</el-button>
      </span>
    </el-dialog>

    <!-- Edit User Dialog -->
    <el-dialog v-model="isEditUserDialogVisible" title="编辑用户" class="dialog" width="50%">
      <el-form :model="currentUser" ref="editUserForm" label-width="80px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="currentUser.userName"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="currentUser.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="currentUser.sex" placeholder="选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="currentUser.age" :min="0" :max="90"></el-input-number>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="currentUser.address"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="currentUser.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="currentUser.phone"></el-input>
        </el-form-item>
        <el-form-item label="积分" prop="points">
          <el-input-number v-model="currentUser.points" :min="0"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditUserDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateUser">更新</el-button>
      </span>
    </el-dialog>
  
</template>

<script setup>
import { ref } from 'vue';
import axiosInstance from '../service/baseService';
import { ElMessage, ElNotification } from 'element-plus';

const users = ref([]);
const searchQuery = ref({ userName: '', phone: '', email: '' });
const dateRange = ref([null, null]);
const isAddUserDialogVisible = ref(false);
const isEditUserDialogVisible = ref(false);
const newUser = ref({ userName: '', password: '', name: '', sex: '', age: null, address: '', email: '', phone: '', points: 0 });
const currentUser = ref({ userId: null, userName: '', name: '', sex: '', age: null, address: '', email: '', phone: '', points: 0 });
const newUserForm = ref(null);
const editUserForm = ref(null);

const rules = {
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }, { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  points: [{ required: true, message: '请输入积分', trigger: 'blur' }]
};

// Fetch users with search and date range filters
const fetchUsers = async () => {

  try {
    const response = await axiosInstance.get('/users/select');
    users.value = response.data;
  } catch (error) {
    console.error('Error fetching users:', error);
    ElMessage.error('获取用户信息失败');
  }
};

// Show add user dialog
const showAddUserDialog = () => {
  newUser.value = { userName: '', password: '', name: '', sex: '', age: null, address: '', email: '', phone: '', points: 0 };
  isAddUserDialogVisible.value = true;
};

// Add a new user
const addUser = async () => {
  try {
    await newUserForm.value.validate();
    await axiosInstance.post('/users/add', newUser.value);
    isAddUserDialogVisible.value = false;
    ElNotification.success({
      title: '成功',
      message: '用户添加成功',
      duration: 3000
    });
    fetchUsers();
  } catch (error) {
    console.error('Error adding user:', error);
    ElMessage.error('添加用户失败');
  }
};

// Show edit user dialog
const showEditUserDialog = (user) => {
  currentUser.value = { ...user };
  isEditUserDialogVisible.value = true;
};



// Update user
const updateUser = async () => {
  try {
    await editUserForm.value.validate();
    await axiosInstance.put(`/users/update/${currentUser.value.userId}`, currentUser.value);
    isEditUserDialogVisible.value = false;
    ElNotification.success({
      title: '成功',
      message: '用户更新成功',
      duration: 3000
    });
    fetchUsers();
  } catch (error) {
    console.error('Error updating user:', error);
    ElMessage.error('更新用户失败');
  }
};

// Delete a user
const deleteUser = async (userId) => {
  console.log(userId);
  try {
    await axiosInstance.delete(`/users/delete/${userId}`);
    ElNotification.success({
      title: '成功',
      message: '用户删除成功',
      duration: 3000
    });
    fetchUsers();
  } catch (error) {
    console.error('Error deleting user:', error);
    ElMessage.error('删除用户失败');
  }
};

// Reset user password
const resetPassword = async (userId) => {
  try {
    await axiosInstance.post(`/users/${userId}/reset-password`);
    ElNotification.success({
      title: '成功',
      message: '密码重置成功',
      duration: 3000
    });
  } catch (error) {
    console.error('Error resetting password:', error);
    ElMessage.error('重置密码失败');
  }
}



// Handle selection change
const handleSelectionChange = (selection) => {
  console.log('Selected users:', selection);
};


const fetchUsersSearch = async () => {
  const params = {
    userName: searchQuery.value.userName,
    phone: searchQuery.value.phone,
    email: searchQuery.value.email,
  };

  try {
    // 注意，axios 将自动处理参数格式
    const response = await axiosInstance.post('/users/search', params);
    users.value = response.data;
  } catch (error) {
    console.error('Error fetching users:', error);
    ElMessage.error('获取用户信息失败');
  }
};

// Initial fetch of users
fetchUsers();
</script>

<style scoped>
.container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.breadcrumb {
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.search-input, .date-picker {
  flex: 1 1 200px;
  max-width: 300px;
}

.table-container {
  margin-top: 20px;
  overflow-x: auto;
}

.dialog {
  max-width: 90%;
}

.dialog-footer {
  text-align: right;
}

.operation-buttons .el-button {
  margin-right: 10px;
}

/* Responsive Design */
@media (max-width: 768px) {
  .search-input, .date-picker {
    flex: 1 1 100%;
    max-width: 100%;
  }
  .operation-buttons .el-button {
    display: block;
    margin-bottom: 5px;
  }
}
</style>
